<template>
  <h2>销售记录</h2>
  <div style="margin-bottom: 10px; display: flex; gap: 8px;">
    <el-input v-model="search.custName" placeholder="客户名称" size="small" style="width:100px;"/>
    <el-input v-model="search.phone" placeholder="客户联系方式" size="small" style="width:100px;"/>
    <el-select v-model="search.grade" placeholder="客户等级" size="small" style="width:90px;">
      <el-option label="1" :value="1"/>
      <el-option label="2" :value="2"/>
      <el-option label="3" :value="3"/>
      <el-option label="4" :value="4"/>
    </el-select>
    <el-select v-model="search.custType" placeholder="客户类型" size="small" style="width:90px;">
      <el-option label="金融" value="金融"/>
      <el-option label="教育" value="教育"/>
      <el-option label="建筑" value="建筑"/>
      <el-option label="餐饮" value="餐饮"/>
      <el-option label="旅游" value="旅游"/>
      <el-option label="环保" value="环保"/>
    </el-select>

    <el-input v-model="search.expectedTransactionAmount" placeholder="预期交易金额不低于" size="small"
              style="width:130px;"/>
    <el-select v-model="search.currentStage" placeholder="交易状态" size="small" style="width:90px;">
      <el-option label="解除" value="解除"/>
      <el-option label="报价" value="报价"/>
      <el-option label="签约" value="签约"/>
    </el-select>
    <el-select v-model="search.sourceChannelId" placeholder="销售渠道" size="small" style="width:90px;">
      <el-option label="自媒体" value="0"/>
      <el-option label="网络推广" value="1"/>
      <el-option label="老客户介绍" value="2"/>
      <el-option label="线下推销" value="3"/>
      <el-option label="二次客户" value="4"/>
    </el-select>
    <el-input v-model="search.empId" placeholder="业务员编号" size="small" style="width:90px;"/>
    <el-button type="primary" size="small" @click="handleSearch">查找</el-button>
    <el-button size="small" @click="resetSearch">重置</el-button>
  </div>

  <el-table :data="tableData" style="width: 100%">
    <!-- 第一层：表头 -->
    <el-table-column fixed prop="custName" label="客户名称" width="100"/>
    <el-table-column prop="phone" label="联系方式" width="120"/>
    <el-table-column prop="grade" label="客户等级" width="100"/>
    <el-table-column prop="custType" label="客户类型" width="100"/>
    <el-table-column prop="expectedTransactionAmount" label="预期交易金额" width="120"/>
    <el-table-column prop="currentStage" label="交易状态" width="100"/>
    <el-table-column prop="sourceChannelId" label="销售渠道" width="100" :formatter="channelFormatter"/>
    <el-table-column prop="empId" label="业务员编号" width="100"/>
    <el-table-column fixed="right" label="操作" min-width="100">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleModify(scope.row)">
          修改
        </el-button>
        <el-button link type="primary" size="small" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </el-table-column>

  </el-table>

  <div class="pagination-block">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 30]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!-- 修改销售记录对话框 -->
  <el-dialog v-model="dialogVisible" title="修改销售记录" width="500px" @close="resetEditForm">
    <div class="form-center">
      <el-form :model="editForm" label-width="auto" style="min-width: 400px">
        <el-form-item label="预期交易金额">
          <el-input v-model="editForm.expectedTransactionAmount"/>
        </el-form-item>
        <el-form-item label="交易状态">
          <el-select v-model="editForm.currentStage" placeholder="交易状态">
            <el-option label="解除" value="解除"/>
            <el-option label="报价" value="报价"/>
            <el-option label="签约" value="签约"/>
          </el-select>
        </el-form-item>
        <el-form-item label="销售渠道">
          <el-select v-model="editForm.sourceChannelId" placeholder="销售渠道">
            <el-option label="自媒体" value="0"/>
            <el-option label="网络推广" value="1"/>
            <el-option label="老客户介绍" value="2"/>
            <el-option label="线下推销" value="3"/>
            <el-option label="二次客户" value="4"/>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEdit">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import axios from "axios";
import {ref, onMounted, watch} from 'vue'
import type {ComponentSize} from 'element-plus'
import {ElMessage} from "element-plus";

// 分页相关
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const size = ref<ComponentSize>('default')
const background = ref(true)
const disabled = ref(false)

// 表格数据
const tableData = ref([])

// 编辑弹窗相关
const dialogVisible = ref(false)
const editForm = ref({
  saleOpportunityId: null,
  expectedTransactionAmount: null,
  currentStage: null,
  sourceChannelId: null,
  // 其它字段...
})

const search = ref({
  custName: null,
  phone: null,
  grade: null,
  custType: null,
  expectedTransactionAmount: null,
  currentStage: null,
  sourceChannelId: null,
  empId: null
});

function channelFormatter(row, column, cellValue) {
  const map = {
    0: '自媒体',
    1: '网络推广',
    2: '老客户介绍',
    3: '线下推销',
    4: '二次客户'
  }
  // 注意cellValue有可能是字符串也可能是数字，这里都兼容
  return map[cellValue] !== undefined ? map[cellValue] : cellValue
}

function handleSearch() {
  loadData()
  // 如果需要请求后端，可以在这里发请求
}

function resetSearch() {
  search.value = {
    custName: null,
    phone: null,
    grade: null,
    custType: null,
    expectedTransactionAmount: null,
    currentStage: null,
    sourceChannelId: null,
    empId: null
  }
  loadData()
}

// 监听分页变化，自动加载数据
watch([currentPage, pageSize], () => {
  loadData()
})

// 页面首次加载
onMounted(() => {
  loadData()
})

// 点击“修改”按钮
function handleModify(row) {
  // 复制 row 数据（推荐深拷贝，防止直接修改表格数据）
  console.log(row)
  editForm.value = {...row}
  dialogVisible.value = true
}

// 重置表单
function resetEditForm() {
  editForm.value = {
    saleOpportunityId: null,
    expectedTransactionAmount: null,
    currentStage: null,
    sourceChannelId: null
  }
}

// 提交修改
function submitEdit() {
  console.log(editForm.value)
  axios.put(`http://localhost:52010/sale/opportunity/${editForm.value.saleOpportunityId}`, editForm.value)
      .then(res => {
        if (res.data.code === 200) {
          ElMessage.success('修改成功')
          dialogVisible.value = false
          loadData() // 编辑成功后刷新表格
        } else {
          ElMessage.error(res.data.message || '修改失败')
        }
      })
      .catch(err => {
        ElMessage.error(err.response?.data?.message || err.message || '请求异常')
      })
}

function loadData() {
  // 你的后端接口如果是 /customer/page/1/5 这样的
  const url = `http://localhost:52010/sale/opportunity/page/${currentPage.value}/${pageSize.value}`

  // 只传递有值的搜索条件
  const params = {}
  Object.keys(search.value).forEach(key => {
    if (search.value[key]) {
      params[key] = search.value[key]
    }
  })

  axios.get(url, {params})
      .then(response => {
        const res = response.data
        if (res.code === 200) {
          /**
           * saleOpportunityId
           * custName
           * phone
           * grade
           * custType
           * expectedTransactionAmount
           * currentStage
           * sourceChannelId
           * empId
           */
          tableData.value = res.data.records || []
          total.value = res.data.total || 0
        } else {
          ElMessage.error(res.message || '请求失败')
        }
      }).catch((error) => {
    const msg = error.response?.data?.message || error.message || '请求异常'
    ElMessage.error(msg)
  })
}

// 可选：分页事件处理器
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1 // 改变pageSize时重置到第一页
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

function handleDelete(row) {
  console.log(row)
  const url = `http://localhost:52010/sale/opportunity/${row.saleOpportunityId}`
  axios.delete(url)
      .then(response => {
        const res = response.data
        if (res.code === 200) {
          ElMessage.success('删除成功')
          loadData() // 这里重新加载数据
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      }).catch((error) => {
    const msg = error.response?.data?.message || error.message || '请求异常'
    ElMessage.error(msg)
  })
}
</script>

<style scoped>
.pagination-block {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin-top: 10px; /* 距离上方10px */
}
</style>